package com.envper.security.service.impl;

import com.envper.mysql.domain.Status;
import com.envper.common.exception.GlobalException;
import com.envper.security.domain.LoginUser;
import com.envper.security.service.LoginUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
    private final LoginUserService loginUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LoginUser loginUser = loginUserService.getLoginUserByUsername(username);
        if(ObjectUtils.isEmpty(loginUser)){
            log.info("登录用户：{} 不存在。", username);
            throw new GlobalException(Status.LONGUSERNOTFOUND);
        } else if (loginUser.getUserDto().getDeleted() == 1){
            log.info("登录用户：{} 已被删除。", username);
            throw new GlobalException(Status.LOGINUSERISDELETED);
        } else if (loginUser.getUserDto().getStatus() == 0){
            log.info("登录用户：{} 已被停用。", username);
            throw new GlobalException(Status.LOGINUSERISDEACTIVATED);
        }
        loginUser.setLoginTime(System.currentTimeMillis());
        return loginUser;
    }
}
